package com.sbr.esbmonitor.wicket.pages.servers;

import org.apache.wicket.PageParameters;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.Model;

import com.sbr.esbmonitor.repositories.ServerRepository;
import com.sbr.esbmonitor.repositories.xml.impl.XMLServerRepository;
import com.sbr.esbmonitor.servicemix.Server;
import com.sbr.esbmonitor.wicket.pages.BasePage;

public class EditServerPage extends BasePage {


	public EditServerPage() {
		IModel<Server> model = new CompoundPropertyModel<Server>(
				new LoadableDetachableModel<Server>() {

					private static final long serialVersionUID = 1L;

					@Override
					protected Server load() {
						return new Server();
					}
				});

		build (model, false);
	}

	public EditServerPage(final PageParameters params) {
		final Long serverId = params.getLong("server");

		IModel<Server> model = new CompoundPropertyModel<Server>(
				new LoadableDetachableModel<Server>() {
					private static final long serialVersionUID = 1L;

					@Override
					protected Server load() {
						return new XMLServerRepository().selectById(serverId);
					}
				});

		build(model, true);
	}

	private void build(IModel<Server> model, final boolean edit) {

		Form<Server> form = new Form<Server>("form", model) {
			private static final long serialVersionUID = 1L;

			@Override
			protected void onSubmit() {
				Server p = getModelObject();
				ServerRepository dao = new XMLServerRepository();
				if (edit) {
					dao.update(p);
				} else {
					dao.insert(p);
				}
				setResponsePage(ListServersPage.class);
			}


		};

		TextField<String> labelField = new TextField<String>("label");
		labelField.setRequired(true);

		form.add(labelField);

		TextField<String> hostNameField = new TextField<String>("hostName");
		hostNameField.setRequired(true);

		form.add(hostNameField);

		Button submit = new Button("submit", new Model<String>(edit ? "MettreAJour()" : "Ajouter()"));
		form.add(submit);

		add(form);

	};
}
